package assist.datastore.parser;

import java.io.Reader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import assist.domain.model.Game;
import assist.domain.model.Player;
import assist.domain.model.Roster;
import assist.domain.model.RosterPlayer;

public class NHLGameInfoHTMLParser
{
    private Source source;
    private Game game;
    
    /**
     * Create the NHLGameInfoHTMLParser for the given season and the given file.
     * @param game The game object, with the gameID already set.
     * @param reader The NHL play by play gamesheet reader stream.
     */
    public NHLGameInfoHTMLParser(final Game game, final Reader reader) 
        throws Exception
    {
        this.source = new Source(reader);
        this.game = game;
        this.parseGameInfo();
        this.parseRosters();
    }
    
    public Game getGame()
    {
        return this.game;
    }

    private void parseRosters()
    {        
        final List<Element> tables = this.source.getAllElements(
                HTMLElementName.TABLE);
        final Element visitorRosterTable = tables.get(10);
        this.parsePlayers(this.game.getVisitorGameStats().getRoster(), visitorRosterTable);
        final Element homeRosterTable = tables.get(11);
        this.parsePlayers(this.game.getHomeGameStats().getRoster(), homeRosterTable);

    }
    
    private void parsePlayers(final Roster roster, final Element rosterTable)
    {        
        final List<Element> playerDataCells = rosterTable.getAllElements(
                HTMLElementName.TD); 
        String playerName = null;
        String position = null;
        Integer number = null;        
        for (int i = 3; i < playerDataCells.size() - 3; i+=3)
        {
            RosterPlayer rosterPlayer = new RosterPlayer();
            position = playerDataCells.get(i+1).getContent().toString().trim();
            playerName = playerDataCells.get(i+2).getContent().toString().trim();
            number = new Integer(
                        playerDataCells.get(i).getContent().toString().trim());
            Player player = new Player();
            playerName = playerName.split("\\(")[0].trim();
            player.setName(playerName);
            
            rosterPlayer.setPlayer(player);
            rosterPlayer.setNumber(number);
            rosterPlayer.setPosition(position);
            roster.add(rosterPlayer); 
        }

    }

    /**
     * Checks the game info in this event file to ensure it is for the correct 
     * game.
     */
    private void parseGameInfo()
    {
        final Element homeTable = this.source.getElementById("Home");
        final Element visitorTable = this.source.getElementById("Visitor");        
        final String homeTeam = this.getTeamFromTable(homeTable);
        final String visitorTeam = this.getTeamFromTable(visitorTable);
        this.game.setHomeTeam(NHLTeamFactory.createFromFullName(homeTeam));
        this.game.setVisitorTeam(NHLTeamFactory.createFromFullName(visitorTeam));    
        final Element gameInfoTable = this.source.getElementById("GameInfo");  
        try
        {
            this.game.setDate(this.getGameDateFromTable(gameInfoTable));             
        }
        catch (ParseException e)
        {            
            System.err.println("TODO: Log parse errors");
            System.err.println("Parse Error for Date:" + e.getMessage());
        }    
    }
    
    private Date getGameDateFromTable(final Element gameInfoTable) 
        throws ParseException
    {
        final List<Element> gameInfoData = gameInfoTable.getAllElements(
                                                HTMLElementName.TD);
        String date = gameInfoData.get(3).getContent().toString();
        SimpleDateFormat dateFmt = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
        return dateFmt.parse(date.trim());
    }
    
    private String getTeamFromTable(final Element teamTable)
    {
        final Element teamRow = 
            teamTable.getAllElements(HTMLElementName.TR).get(3);
        final String textContent = 
            teamRow.getContent().getTextExtractor().toString();
        return textContent.replaceAll("Game.*", "").trim();       
    }        
}
